package handler

import (
	"github.com/gin-gonic/gin"
	"smart-planet-mgr/modelr"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	cont := c.PostForm("cont")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))
	life := modelr.Life{
		Title:  title,
		Cont:   cont,
		UserID: userID,
	}
	err := modelr.DB.Debug().Create(&life).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加成功",
		})
	}
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := modelr.DB.Delete(&modelr.Life{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
	}
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var count int64
	modelr.DB.Model(&modelr.Life{}).Count(&count)

	var user []modelr.Life
	err := modelr.DB.Offset(offset).Limit(size).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"user":  user,
			},
		})
	}
}
